package com.microweb.toastmaster.webapp.action;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import com.microweb.toastmaster.webapp.action.BaseFormController;
import com.microweb.toastmaster.model.TMProject;
import com.microweb.toastmaster.service.TMProjectManager;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

public class TMProjectFormController extends BaseFormController {
    private TMProjectManager tMProjectManager = null;

    public void setTMProjectManager(TMProjectManager tMProjectManager) {
        this.tMProjectManager = tMProjectManager;
    }
    public TMProjectFormController() {
        setCommandName("tMProject");
        setCommandClass(TMProject.class);
    }

    protected Object formBackingObject(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");
        TMProject tMProject = null;

        if (!StringUtils.isEmpty(id)) {
            tMProject = tMProjectManager.getTMProject(id);
        } else {
            tMProject = new TMProject();
        }

        return tMProject;
    }

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'onSubmit' method...");
        }

        TMProject tMProject = (TMProject) command;
        boolean isNew = (tMProject.getId() == null);
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            tMProjectManager.removeTMProject(tMProject.getId().toString());

            saveMessage(request, getText("tMProject.deleted", locale));
        } else {
            tMProjectManager.saveTMProject(tMProject);

            String key = (isNew) ? "tMProject.added" : "tMProject.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                return new ModelAndView("redirect:editTMProject.html", "id", tMProject.getId());
            }
        }

        return new ModelAndView(getSuccessView());
    }
}
